<script setup>
import { h, compile, ref, nextTick } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import FunctionalIcons from '@/components/FunctioalIcon.vue';
import tool from "@/utils/tool";
import userApi from "@/api/userApi";

const router = useRouter();
const selectedKeys = ref([]);
const visible = ref(false);
const canClose = ref(true);
const submitForm = ref();
const loginId = tool.data.get("loginId");

const submitData = ref({});
const menus = ref([]);

const back = () => {
  router.back();
};
const onClickMenuItem = (key) => {
  selectedKeys.value = [key];
  router.push({
    name: key,
  });
};
const collapsed = ref(false);
const onCollapse = (val, type) => {
  collapsed.value = val;
};

const showUpdatePwd = () => {
  visible.value = true;
  submitForm.value.resetFields();
};

const handleSubmitSuccess = (values) => {
  values.id = loginId;
  if (values.newPwd !== values.surePwd) {
    Message.warning("两次输入密码不一致");
    return;
  }
  userApi.updatePwd(values).then((res) => {
    Message.success("修改成功，请重新登录");
    tool.data.remove("tokenValue");
    router.push({
      path: "/login",
    });
  });
};

const handleSelect = (value) => {
  if (value == 'updatePwd') {
    showUpdatePwd();
  } else {
    loginout();
  }
}

const loginout = () => {
  tool.data.remove("tokenValue");
  router.push({
    path: "/login",
  });
};

const queryMenuTree = () => {
  let userId = tool.data.get("loginId");
  userApi.queryMenuTree({ userId: userId }).then(res => {
    let menuItems = [];
    let hasHomeMenu = false;
    res.forEach(item => {
      menuItems.push(item);
      if (item.code == 'dashboard') {
        hasHomeMenu = true
      }
    })
    menus.value = menuItems;
    if (hasHomeMenu) {
      router.push({
        name: "dashboard",
      });
    }
  })
}

const queryPermissions = () => {
  let userId = tool.data.get("loginId");
  userApi.queryPermissions({ userId: userId }).then(res => {
    tool.data.set('permissions', res);
    isUpdatePwd();
  })
}

const isUpdatePwd = () => {
  // userApi.queryIsUpdatePwd().then(res => {
  //   if (!res) {
  //     visible.value = true;
  //     canClose.value = false;
  //   }
  // })
};

queryMenuTree();
queryPermissions();
</script>

<template>
  <a-layout class="layout-main">
    <a-layout-sider breakpoint="lg" :width="collapsed ? 60 : 220" style="flex-direction: column;" class="menu-demo">
      <div class="logo flex flex-v-center">
        <img src="@/assets/logo.png" style="width: 30px; height: 30px" alt="" />
        <span v-if="!collapsed" style="margin-left: 10px;">浮遇纪</span>
      </div>
      <a-menu style="height: 90%;" class="flex1" showCollapseButton :selected-keys="selectedKeys"
        @menu-item-click="onClickMenuItem" breakpoint="xl" @collapse="onCollapse">
        <div v-for="menu in menus" :key="menu.code">
          <a-menu-item v-if="!menu.children || menu.children.length == 0" :key="menu.code">
            <template #icon>
              <functional-icons :icon="menu.iconName"></functional-icons>
            </template>
            {{ menu.name }}
          </a-menu-item>
          <a-sub-menu v-if="menu.children && menu.children.length > 0" :key="menu.code">
            <template #icon>
              <functional-icons :icon="menu.iconName"></functional-icons>
            </template>

            <template #title>{{ menu.name }}</template>
            <a-menu-item v-for="childMenu in menu.children" :key="childMenu.code">{{ childMenu.name }}</a-menu-item>
          </a-sub-menu>
        </div>
      </a-menu>
    </a-layout-sider>
    <a-layout id="layout-main">
      <a-layout-header style="height: 65px">
        <div class="flex flex-v-center" style="height: 100%;padding:0 16px;">
          <div class="flex1">
            <a-button type="outline" shape="round" @click="back">

              <template #icon>
                <icon-left />
              </template>返回</a-button>
          </div>
          <div>
            <a-dropdown @select="handleSelect">
              <a-button type="primary" shape="circle">

                <template #icon>
                  <icon-user />
                </template>
              </a-button>

              <template #content>
                <a-doption value="updatePwd">
                  <template #icon>
                    <icon-unlock />
                  </template>
                  修改密码</a-doption>
                <a-doption value="loginout">

                  <template #icon>
                    <icon-import />
                  </template>
                  退出登录</a-doption>
              </template>
            </a-dropdown>
          </div>
        </div>
        <div style="clear: both"></div>
      </a-layout-header>
      <a-layout style="padding: 1px" class="bg-base">
        <a-layout-content>
          <RouterView></RouterView>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </a-layout>
  <a-modal v-model:visible="visible" title="修改密码" :footer="null" :closable="canClose" :mask-closable="false">
    <a-form ref="submitForm" size="large" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
      :model="submitData" @submit-success="handleSubmitSuccess">
      <a-form-item field="oldPwd" label="原密码" :rules="[
        { required: true, message: '请输入原密码' },
        { minLength: 6, message: '密码不能少于6位' },
      ]
        ">
        <a-input type="password" v-model.trim="submitData.oldPwd" placeholder="请输入原密码" />
      </a-form-item>
      <a-form-item field="newPwd" label="新密码" :rules="[
        { required: true, message: '请输入新密码' },
        { minLength: 6, message: '密码不能少于6位' },
      ]
        ">
        <a-input type="password" v-model.trim="submitData.newPwd" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item field="surePwd" label="确认密码" :rules="[
        { required: true, message: '请再次输入新密码' },
        { minLength: 6, message: '密码不能少于6位' },
      ]
        ">
        <a-input type="password" v-model.trim="submitData.surePwd" placeholder="请再次输入新密码" />
      </a-form-item>
      <a-form-item>
        <div style="color: #999; font-size: 12px">
          注：若未修改初始密码，每次登录系统都会默认弹出修改密码窗口
        </div>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button html-type="submit" type="primary">保存</a-button>
          <a-button v-if="canClose" @click="() => {
            visible = false;
          }
            ">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.logo {
  font-size: 18px;
  text-align: center;
  color: #1c1f23;
  /* padding: 12px; */
  height: 55px;
  line-height: 55px;
  font-family: Inter, -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC,
    Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial,
    sans-serif;
  font-weight: 600;
  padding-left: 10px;
}

.demo-basic {
  padding: 10px;
  padding-top: 20px;
  width: 200px;
  background-color: var(--color-bg-popup);
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
}
</style>
